/**
 * 版权所有(C)，上海勾芒信息科技，2017，所有权利保留。
 * 
 * 项目名：	cards-web
 * 文件名：	QrAppCodeRequestExecutor.java
 * 模块说明：	
 * 修改历史：
 * 2017年6月30日 - Debenson - 创建。
 */
package cn.binarywang.wx.miniapp.api.impl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;

import cn.binarywang.wx.miniapp.api.impl.WxMaQrcodeServiceExImpl.QrAppCodeRequest;
import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.util.fs.FileUtils;
import me.chanjar.weixin.common.util.http.RequestExecutor;
import me.chanjar.weixin.common.util.http.RequestHttp;
import me.chanjar.weixin.common.util.http.apache.InputStreamResponseHandler;
import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler;

/**
 * @author Debenson
 * @since 0.1
 */
public class QrAppCodeRequestExecutor implements RequestExecutor<File, QrAppCodeRequest> {
  protected RequestHttp<CloseableHttpClient, HttpHost> requestHttp;

  @SuppressWarnings({
      "rawtypes", "unchecked" })
  public QrAppCodeRequestExecutor(RequestHttp requestHttp) {
    this.requestHttp = requestHttp;
  }

  @Override
  public File execute(String uri, QrAppCodeRequest req) throws WxErrorException, IOException {
    HttpPost httpPost = new HttpPost(uri);
    if (requestHttp.getRequestHttpProxy() != null) {
      httpPost
          .setConfig(RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build());
    }
    httpPost.setEntity(new StringEntity(req.toString()));

    try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost);
        InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response);) {
      Header[] contentTypeHeader = response.getHeaders("Content-Type");
      if (contentTypeHeader != null && contentTypeHeader.length > 0) {
        String respContentType = contentTypeHeader[0].getValue();
        if (respContentType.toLowerCase()
            .indexOf(ContentType.TEXT_PLAIN.getMimeType().toLowerCase()) >= 0
            || respContentType.toLowerCase()
                .indexOf(ContentType.APPLICATION_JSON.getMimeType().toLowerCase()) >= 0) {
          String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
          throw new WxErrorException(WxError.fromJson(responseContent));
        }
      }
      return FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), "jpg");
    } finally {
      httpPost.releaseConnection();
    }
  }

}
